<template>
  <div class="wrapper">
    <van-pull-refresh v-model="isLoad"
                      @refresh="onRefresh"
                      class="pull"
                      :disabled="disabled">
      <common-scroll ref="scroll"
                     :data="recommend"
                     class="scroll"
                     @scroll='handlescroll'
                     @scrollend="handleScrollend"
                     :listenScroll="listenScroll"
                     :class="{marTop: isrefresh}">
        <div>
          <home-header ref="header"></home-header>
          <home-swiper :list="swiperList"
                       @load="loadDataed"></home-swiper>
          <home-icon :iconList="iconList"></home-icon>
          <home-special :list="article"></home-special>
          <common-loading v-show="!recommend.length"
                          class="loading"></common-loading>
          <home-recommend :recommend="recommend"></home-recommend>
          <div class="more"
               v-show="load">加载中...</div>
          <div class="more"
               v-show="finish">没有更多</div>
        </div>
      </common-scroll>
    </van-pull-refresh>

    <common-skip></common-skip>
    <el-amap vid="amap"
             :plugin="plugin"></el-amap>
  </div>
</template>

<script>
import HomeSwiper from './components/Swiper.vue'
import HomeHeader from './components/Header'
import HomeIcon from './components/Icon'
import HomeSpecial from './components/Special'
import HomeRecommend from './components/Recommend'
import CommonSkip from 'common/skip/Skip'
import CommonScroll from 'common/scroll/Scroll'
import CommonLoading from 'common/loading/Loading'
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'Home',
  components: {
    HomeSwiper,
    HomeHeader,
    HomeIcon,
    HomeSpecial,
    HomeRecommend,
    CommonSkip,
    CommonScroll,
    CommonLoading
  },
  data () {
    let _this = this
    return {
      swiperList: [],
      iconList: [],
      specialOffer: [],
      recommend: [],
      article: [],
      page: 1,
      timer: null,
      isLoad: false,
      isLoading: false,
      isrefresh: false,
      disabled: false,
      load: false,
      finish: false,
      scrollHeight: 0,
      plugin: [{
        pName: 'Geolocation',
        events: {
          init (o) {
            _this.map = o
            // o 是高德地图定位插件实例
            return new Promise((resolve, reject) => {
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  resolve(result)
                } else {
                  reject(result)
                }
              })
            })
          }
        }
      }],
      locationCity: '',
      locationStreet: '',
      map: ''
    }
  },
  methods: {
    // 轮播图获取
    getSwiper () {
      this.$api.index.indexSwiper({ type: 1 })
        .then(this.getSwiperSucc)
        .catch((e) => {
          console.log(e)
        })
    },
    getSwiperSucc (res) {
      res = res.data
      if (this.$api.CODE_OK === res.code && res.data) {
        const data = res.data
        this.swiperList = data
      }
    },
    onRefresh () {
      setTimeout(() => {
        this.$toast('刷新成功')
        this.getSwiper()
        this.getIcon()
        this.isLoad = false
      }, 200)
    },
    // icon获取
    getIcon () {
      this.$api.classify.classifyAll()
        .then(this.getIconSucc)
        .catch((e) => { })
    },
    getIconSucc (res) {
      res = res.data
      if (this.$api.CODE_OK === res.code && res.data) {
        const data = res.data
        this.iconList = data
      }
    },
    getRecommendInfo () {
      this.$api.index.indexRecommend({ longitude: 108.90688, latitude: 34.15775, page: this.page })
        .then(this.getRecommendSucc)
        .catch((e) => {
          console.log(e)
        })
    },
    getRecommendSucc (res) {
      res = res.data
      if (this.$api.CODE_OK === res.code && res.data) {
        const data = res.data
        this.recommend.push(...data)
        if (data.length === 0) {
          this.load = false
          this.finish = true
        }
      }
    },
    // 文章获取
    getArticle () {
      this.$api.index.getArticle()
        .then(this.getArticleSucc)
    },
    getArticleSucc (res) {
      res = res.data
      if (res.code === this.$api.CODE_OK && res.data) {
        const data = res.data
        this.article = data
      }
    },
    loadDataed () {
      if (!this.checkLoaded) {
        this.$refs.scroll.refresh()
        this.checkLoaded = true
      }
    },
    loadMore () {
      this.page++
      if (this.page > 5) {
        return false
      }
      this.getRecommendInfo()
    },
    handlescroll (pos) {
      if (pos.y > 50) {
        this.isrefresh = true
      }
    },
    handleScrollEnd (pos) {
      if (pos.y > 50) {
        this.getIcon()
        this.getRecommendInfo()
        this.$refs.scroll.finishPullDown()
        this.isrefresh = false
      }
    },
    getLocation (o) {
      const events = this.plugin[0].events.init(o)
      events.then((res) => {
        o.options.maximumAge = 0
        let city = res.addressComponent.city
        let street = res.addressComponent.street
        city = city.substring(0, city.length - 1)
        this.$localStorage.set('city', city)
        this.$localStorage.set('LocationCity', city)
        this.locationCity = city
        this.locationStreet = street
        this.changeStreet(street)
        this.$localStorage.set('street', street)
        const sellerCity = this.$localStorage.get('city')
        const location = {
          local_city: city,
          select_city: sellerCity,
          longitude: res.position.O,
          latitude: res.position.P,
          page: 1
        }
        this.$localStorage.set('locationData', JSON.stringify(location))
      }).catch((e) => {
        window.close()
      })
    },
    ...mapMutations({
      changeStreet: 'changeStreet'
    }),
    handleScrollend (pos) {
      this.scrollHeight = -pos.y
    }
  },
  watch: {
    scrollHeight (newY) {
      if (newY > 50 && !this.finish) {
        this.page++
        this.load = true
      }
      this.disabled = newY > 0
    },
    page (page) {
      if (this.load && !this.finish) {
        setTimeout(() => {
          this.getRecommendInfo()
          this.load = false
          this.$refs.scroll.finishPullUp()
          this.$refs.scroll.refresh()
        }, 200)
      }
    },
    recommend () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.$refs.scroll.pullingDownRefresh()
        this.timer = null
      }, 20)
    },
    locationCity (city) {
      let history = this.$localStorage.get('history')
      if (history !== null) {
        history = JSON.parse(history)
        history[0] = city
        history = [...new Set(history)]
        this.$localStorage.set('history', JSON.stringify(history))
      } else {
        this.$localStorage.set('LocationCity', city)
        const cities = []
        cities.push(city)
        this.$localStorage.set('history', JSON.stringify(cities))
      }
    },
    map (o) {
      this.getLocation(o)
    },
    locationStreet (street) {
      this.$localStorage.set('street', street)
    }
  },
  computed: {
    pages () {
      return this.page > 5
    },
    ...mapState(['historyCity'])
  },
  activated () {
    setTimeout(() => {
      this.$refs.scroll._initalScroll()
    }, 20)
  },
  created () {
    this.listenScroll = true
    this.getSwiper()
    this.getIcon()
    this.getRecommendInfo()
    this.getArticle()
  },
  destroyed () {
    this.$refs.scroll = null
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/variable.styl'

.wrapper >>> .van-pull-refresh__track
  width 100%
  height 100%

.wrapper
  touch-action none

  .refresh
    height 200px
    background-color #f60

.wrap-enter-active .wrap-leave-active
  transition all 0.6s

.wrap-enter .wrap-leave-active
  height 0

.pull
  position absolute
  width 100%
  height 100%
  top 0
  left 0
  bottom 0
  right 0
  background-color $bgcWh

.more
  width 100%
  height 100px
  line-height 100px
  text-align center
  font-size $fzFourthly
  color $graySecond
  padding-bottom 200px
  box-sizing border-box
</style>
